// ActionScript file
import Modules.NavigationInfo;
import Modules.Opportunity.OpportunityProductsDetail;
import Modules.PostLogin;
import Modules.Windows.CMDWindow;

import com.desidea.common.CommonClass;
import com.desidea.common.MenuConstants;
import com.desidea.components.grid.SuperGrid;
import com.desidea.components.grid.SuperGridEvent;
import com.desidea.components.grid.button.SuperGridButton;
import com.desidea.utils.DirtyChecker;
import com.desidea.utils.IDirtyChecker;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import flash.events.MouseEvent;

import mx.controls.Alert;
import mx.controls.LinkButton;
import mx.core.Application;
import mx.events.ValidationResultEvent;
import mx.managers.PopUpManager;
import mx.rpc.events.FaultEvent;
import mx.utils.StringUtil;

private var _btnEditCancel:LinkButton;
private var _btnAddProduct:LinkButton;

private var _key:String = "";
private var _mode:String = "view";//Constants.MODE_ADD;
private var _modeSet:Boolean = false;
private var _creationCompleted:Boolean = false;
private var oppdetails:XML;
private var _accountGUID:String = "";

public function get mode():String{
	return _mode;
}

public function set mode(value:String):void{
	this._mode = value;
	this._modeSet = true;
	
//	setScreenMode();
//	this.loadData();
}

public function get key():String{
	return _key;
}

public function set key(value:String):void{
	this._key = value;
}

public function get accountGUID():String{
	return _accountGUID;
}

public function set accountGUID(value:String):void{
	this._accountGUID = value;
}

private function typeSelectionChange():void{
	cmbContact.dataProvider = oppdetails.CONTACTS.entry.(@accountid == cmbAccountName.selectedItem.@id) as XMLList;
	cmbContact.selectedIndex = 0;
	cmbContact.selectedItem = (oppdetails.CONTACTS.entry.(@id == oppdetails.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML;
}

private function setScreenMode():void{
	if(!_creationCompleted) return;
	
	if(this.mode == SuperGridButton.MODE_VIEW || this.mode == SuperGridButton.MODE_VIEWICON){
		frmOpportunityInfo.enabled = false;
		btnSubmit.enabled = false;
		cmbAccountName.selectedItem = (oppdetails.ACCOUNTS.entry.(@id == oppdetails.RELATIONS.RELATION.(@type == "OPPORTUNITY_ACCOUNT"))[0]) as XML;
		this.lblTitle.text = "View Opportunity Detail";

	}else if(this.mode == SuperGridButton.MODE_EDIT){		//MODE_EDIT = create new
		frmOpportunityInfo.enabled = true;
		cmbOppOwner.selectedItem = (oppdetails.USERS.entry.(@id == CommonClass.UserID.toString())[0]) as XML;
		btnSubmit.enabled = true;
		cmbAccountName.enabled = true;
		cmbOppOwner.enabled = false;
		_btnEditCancel.enabled = false;
		this.lblTitle.text = "New Opportunity";
		
		this.pnlProductInfo.height = 0;
		this.pnlProductInfo.visible = false;
	}
}


private function windowCreated():void{

	_btnEditCancel = new LinkButton();
	_btnEditCancel.label = "Edit";	
	_btnEditCancel.height = this.pnlOpportunityInfo.ToolBox.height - 2;
	_btnEditCancel.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('editdetails'); });
	this.pnlOpportunityInfo.ToolBox.addChild(_btnEditCancel);
	
	_btnAddProduct = new LinkButton();
	_btnAddProduct.label = "Add";	
	_btnAddProduct.height = this.pnlProductInfo.ToolBox.height - 2;
	_btnAddProduct.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('addproduct'); });
	this.pnlProductInfo.ToolBox.addChild(_btnAddProduct);
	
	this._creationCompleted = true;
	this.loadData();
	this.loadOpportunityProducts();

	this.oppsProductsGrid.addEventListener(SuperGridEvent.CLICKED, gridButtonColumnClicked);

}


private function loadData():void{
	if( DirtyChecker.getInstance().isDirty){
		if (DirtyChecker.getInstance().sourceContainer is IDirtyChecker){
			(DirtyChecker.getInstance().sourceContainer as IDirtyChecker).promptToSave();
		}else{
			Alert.show("Save & Proceed");
		}
		return;
	}else{
		DirtyChecker.getInstance().resetDirtyChecker();
	}
	
	var params:String = "OPERATION=OPPORTUNITY_GETDETAILS" +
						"&PKID=" + escape(StringUtil.trim(this.key)) +
						"&OWNERID=" + CommonClass.UserID;
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForOpportunityDetails);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);

//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForOpportunityDetails(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	oppdetails = XML(event.result);
	if(oppdetails.RESPONSE.RESULT == "E"){
		Alert.show(oppdetails.RESPONSE.MESSAGE);
	}else if(oppdetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(oppdetails);
		setScreenMode();
		typeSelectionChange();
	}
}

private function partnerServiceFaultHandler(event:FaultEvent):void{
//	BusySpinner.getInstance().stop();
	Alert.show(event.fault.toString());
}

public function loadOpportunityProducts():void{
	if(this.key.length>0){
		var params:String = "OPERATION=OPP_PROD_LIST" +
							"&PKID=" + escape(StringUtil.trim(this.key));
		
		var ws:PartnerService = new PartnerService();
		ws.addprocessServiceRequestEventListener(callForOpportunityProducts);
		ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
		ws.processServiceRequest(params);
	}
}
private function callForOpportunityProducts(event:ProcessServiceRequestResultEvent):void{
	var prods:XML = XML(event.result);
	if(prods.RESPONSE.RESULT == "E"){
		Alert.show(prods.RESPONSE.MESSAGE);
	}else if(prods.RESPONSE.RESULT == 'S'){
		this.oppsProductsGrid.dataProvider = prods;
		setColumnWidths(this.oppsProductsGrid);
	}
}

private function setDataOnControls(response:XML):void{
	cmbOppOwner.dataProvider = new XML(response.USERS).entry as XMLList;
	cmbOppOwner.selectedIndex = 0;
	cmbOppOwner.selectedItem = (response.USERS.entry.(@id == response.RELATIONS.RELATION.(@type == "OWNER"))[0]) as XML
	
	cmbOppType.dataProvider = new XML(response.OPPORTUNITYTYPES).entry as XMLList;
	cmbOppType.selectedIndex = 0;
	cmbOppType.selectedItem = (response.OPPORTUNITYTYPES.entry.(@id == response.OPPTYPEID)[0]) as XML;
	
	cmbAccountName.dataProvider = response.ACCOUNTS.entry as XMLList;
	cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@id == response.RELATIONS.RELATION.(@type == "OPPORTUNITY_ACCOUNT"))[0]) as XML;
	cmbAccountName.selectedIndex = (cmbAccountName.selectedIndex<0)?0:cmbAccountName.selectedIndex;
	
	cmbStatus.dataProvider = new XML(response.STATUS).entry as XMLList;
	cmbStatus.selectedIndex = 0;
	cmbStatus.selectedItem = (response.STATUS.entry.(@id == response.STATUSID)[0]) as XML
	
	cmbStage.dataProvider = new XML(response.OPPSTAGES).entry as XMLList;
	cmbStage.selectedIndex = 0;
	cmbStage.selectedItem = (response.OPPSTAGES.entry.(@id == response.OPPSTAGEID)[0]) as XML
	
	cmbResellerName.dataProvider = new XML(response.RESELLERACCOUNTS).entry as XMLList;
	cmbResellerName.selectedIndex = 0;
	cmbResellerName.selectedItem = (response.RESELLERACCOUNTS.entry.(@id == response.RESELLERNO)[0]) as XML
	
	cmbReferralSource.dataProvider = new XML(response.OPPREFERRALS).entry as XMLList;
	cmbReferralSource.selectedIndex = 0;
	cmbReferralSource.selectedItem = (response.OPPREFERRALS.entry.(@id == response.OPPREFERRALID)[0]) as XML
	
	CommonClass.setDataOnComponents(this.txtOppDesc, response);
	CommonClass.setDataOnComponents(this.txtRevenue, response);
	CommonClass.setDataOnComponents(this.txtProbability, response);
	CommonClass.setDataOnComponents(this.txtRevenueTotal, response);
	CommonClass.setDataOnComponents(this.txtQuantityTotal, response);
	CommonClass.setDataOnComponents(this.dtClose, response);
	CommonClass.setDataOnComponents(this.dtMilestone, response);
	CommonClass.setDataOnComponents(this.txtApplication, response);
	CommonClass.setDataOnComponents(this.txtCompetitors, response);
	CommonClass.setDataOnComponents(this.txtNotes, response);

	cmbContact.dataProvider = new XML(response.CONTACTS).entry.(@accountid == cmbAccountName.selectedItem.@id) as XMLList;
	cmbContact.selectedIndex = 0;
	cmbContact.selectedItem = (response.CONTACTS.entry.(@id == response.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML

	if(this.accountGUID.length >0){
		cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@guid == this.accountGUID.toUpperCase())[0]) as XML;
	}	
}


private function getPostData():String{
	var postData:String = new String();
	postData += "OPPORTUNITYID=" + (oppdetails.OPPORTUNITYID.toString())		+ "&";
	postData += "OPPORTUNITYGUID=" + (oppdetails.OPPORTUNITYGUID.toString())	+ "&";

//	postData += "OPPREFERRALID=" + (oppdetails.OPPREFERRALID.toString())		+ "&";
	postData += "NOTEID=" + (oppdetails.NOTEID.toString())						+ "&";
	postData += "USERID=" + (CommonClass.UserID)								+ "&";
				
	postData += (CommonClass.preparePostString(this.txtOppDesc))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbOppType))				+ "&";
	postData += (CommonClass.preparePostString(this.txtRevenue))				+ "&";
	postData += (CommonClass.preparePostString(this.txtProbability))			+ "&";
	postData += (CommonClass.preparePostString(this.txtRevenueTotal))			+ "&";
	postData += (CommonClass.preparePostString(this.txtQuantityTotal))			+ "&";
	postData += (CommonClass.preparePostString(this.dtClose))					+ "&";
	postData += (CommonClass.preparePostString(this.dtMilestone))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbStatus))					+ "&";
	postData += (CommonClass.preparePostString(this.txtApplication))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbStage))					+ "&";
	postData += (CommonClass.preparePostString(this.txtCompetitors))			+ "&";
	postData += (CommonClass.preparePostString(this.txtNotes))					+ "&";
	postData += (CommonClass.preparePostString(this.cmbResellerName))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbReferralSource))			+ "&";

	postData += (CommonClass.preparePostString(this.cmbOppOwner))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbContact))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbAccountName));
	return postData;	
}

private function saveData(action:String, data:String=""):void{
	var params:String = "OPERATION=OPPORTUNITY_UPDATEDETAILS" +
						(data.length>0?"&":"") +data;
//	Alert.show(params);
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateOppsDetails);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.parentApplication);
}


private function callForUpdateOppsDetails(event:ProcessServiceRequestResultEvent):void{
	var response:XML = XML(event.result);
//	BusySpinner.getInstance().stop();
//	Alert.show(response.toString());
	if(response.RESPONSE.RESULT == "S"){
		DirtyChecker.getInstance().resetDirtyChecker();

		var ni:NavigationInfo = new NavigationInfo("",MenuConstants.CMD,MenuConstants.MY_ACCOUNT,String(this.cmbAccountName.selectedItem.@guid));
		(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(ni);

//		handleCancelClick();

	}else{
		Alert.show( String(response.toString()) );	
	}	
	
}


private function init():void{
	this.txtNotes.linkTextInput.visible = false;
	this.txtNotes._RichTextEditor_VRule2.visible = false;
}

private function onClick(mode:String):void{
	switch(mode){
		case "editdetails":
			frmOpportunityInfo.enabled = true;
			btnSubmit.enabled = true;
			cmbAccountName.enabled = false;
			cmbOppOwner.enabled = false;
			_btnEditCancel.enabled = false;
			this.lblTitle.text = "Edit Opportunity Detail";
			break;
		case "addproduct":
			showDetail(SuperGridButton.MODE_EDIT,"");
			break;
		
	}
}

private function showDetail(mode:String, key:String=""):void{
	
	var cd:OpportunityProductsDetail = new OpportunityProductsDetail();
	cd.key = key;
	cd.caller = this;
	cd.opportunityGUID = this.key;
	
	PopUpManager.addPopUp(cd,this,true);
	PopUpManager.centerPopUp(cd);
}

private function buttonClick(eventType:String):void{
	switch(eventType){
		case "save":
			handleSubmitClick();
			break;
		case "cancel":
			handleCancelClick();
			break;
		default:
			Alert.show( "Yet to Implement : " + eventType);
	}
}

private function handleCancelClick():void{
	(this.parentDocument as CMDWindow).NavInfo = null;
	(this.parentDocument as CMDWindow).loadModule();
}

private function handleSubmitClick():void{
	if(validate()){
		saveData("", getPostData());
	}else{
		Alert.show("Please provide missing/incorrect details before saving","Save");
	}
}
private function validate():Boolean{
	return 	(descV.validate().type == ValidationResultEvent.VALID) &&
			(oppTypeV.validate().type == ValidationResultEvent.VALID) &&
			(accNameV.validate().type == ValidationResultEvent.VALID) &&
			(revnV.validate().type == ValidationResultEvent.VALID) &&
			(probV.validate().type == ValidationResultEvent.VALID) &&
			(revnTotalV.validate().type == ValidationResultEvent.VALID) &&
			(qtyV.validate().type == ValidationResultEvent.VALID) &&
			(closedtV.validate().type == ValidationResultEvent.VALID) &&
			(milestonedtV.validate().type == ValidationResultEvent.VALID) &&
			(statusV.validate().type == ValidationResultEvent.VALID) &&
			(stageV.validate().type == ValidationResultEvent.VALID) &&
			(refsrcV.validate().type == ValidationResultEvent.VALID) &&
			(contactV.validate().type == ValidationResultEvent.VALID);
}

private function setColumnWidths(grid:SuperGrid):void{
	CommonClass.setColumnWidth(grid, 1, 180);
	CommonClass.setColumnWidth(grid, 2, 90,"right");
	CommonClass.setColumnWidth(grid, 3, 90,"right");
	CommonClass.setColumnWidth(grid, 4, 90,"right");
	CommonClass.setColumnWidth(grid, 5, 90,"right");
}


private function gridButtonColumnClicked(event:SuperGridEvent):void{
	handleGridButtonClick(event);
}

private function handleGridButtonClick(event:SuperGridEvent, moduleCode:String = null):void{
	var mode:String =  String(event.data.linkId).toLowerCase();
	
	if(mode == SuperGridButton.MODE_EDIT || mode == SuperGridButton.MODE_VIEW || mode == SuperGridButton.MODE_VIEWICON){
		showDetail(mode, event.data.data["key"].toString());
	}else{
		Alert.show("Mode : " + mode + " not handled");
	}
	
}
